package cn.sinata.wanglin.neighbor.activity;

import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.Editable;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;

import com.google.gson.JsonObject;
import com.hyphenate.easeui.domain.EaseEmojicon;
import com.hyphenate.easeui.domain.EaseEmojiconGroupEntity;
import com.hyphenate.easeui.model.EaseDefaultEmojiconDatas;
import com.hyphenate.easeui.utils.EaseSmileUtils;
import com.hyphenate.easeui.widget.emojicon.EaseEmojiconMenu;
import com.hyphenate.easeui.widget.emojicon.EaseEmojiconMenuBase;
import com.xilada.xldutils.activitys.BaseActivity;
import com.xilada.xldutils.activitys.TitleActivity;
import com.xilada.xldutils.utils.ActivityUtil;
import com.xilada.xldutils.utils.SharedPreferencesUtils;
import com.xilada.xldutils.utils.Utils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnTextChanged;
import cn.sinata.wanglin.R;
import cn.sinata.wanglin.commonutils.Constant;
import cn.sinata.wanglin.model.Circle;
import cn.sinata.wanglin.model.Comment;
import cn.sinata.wanglin.model.Like;
import cn.sinata.wanglin.model.LikeData;
import cn.sinata.wanglin.neighbor.controller.FriendCircleListener;
import cn.sinata.wanglin.neighbor.view.CircleDetailView;
import cn.sinata.wanglin.net.HttpManager;
import cn.sinata.wanglin.net.model.util.ResultDataSubscriber;

public class CircleDetailActivity extends TitleActivity {

    public static final int RESULT_DELETE = 66;
    @BindView(R.id.circleView)
    CircleDetailView circleView;
    @BindView(R.id.mSwipeRefreshLayout)
    SwipeRefreshLayout mSwipeRefreshLayout;
    @BindView(R.id.ease_layout_emojicon_menu)
    EaseEmojiconMenu emojiconMenu;
    @BindView(R.id.et_comment)
    EditText et_comment;
    @BindView(R.id.expressionView)
    TextView expressionView;
    @BindView(R.id.tv_action)
    TextView tv_action;
    @BindView(R.id.scroll_view)
    ScrollView scroll_view;
    private String id;
    private String userId;
    private int position;
    private Circle mCircle;
    private int type = 0;
    private String toUser ;
    private String commentId ;
    private Handler handler;

    @Override
    protected int setContentId() {
        return R.layout.activity_circle_detail;
    }

    @Override
    protected void initView() {
        super.initView();
        setTitle("详情");

        id = getIntent().getStringExtra("id");
        toUser = getIntent().getStringExtra("toUser");
        position = getIntent().getIntExtra("position",0);
        userId = SharedPreferencesUtils.getString(Constant.SP_USERID);

        List<EaseEmojiconGroupEntity> emojiconGroupList = new ArrayList<>();
        emojiconGroupList.add(new EaseEmojiconGroupEntity(R.drawable.ee_1,  Arrays.asList(EaseDefaultEmojiconDatas.getData())));
        emojiconMenu.init(emojiconGroupList);
        emojiconMenu.setEmojiconMenuListener(new EaseEmojiconMenuBase.EaseEmojiconMenuListener() {
            @Override
            public void onExpressionClicked(EaseEmojicon emojicon) {
                int selection = et_comment.getSelectionEnd();
                et_comment.getText().insert(selection,EaseSmileUtils.getSmiledText(mContext,emojicon.getEmojiText()));
//                et_comment.append(EaseSmileUtils.getSmiledText(mContext,emojicon.getEmojiText()));
            }

            @Override
            public void onDeleteImageClicked() {
                if (!TextUtils.isEmpty(et_comment.getText())) {
                    KeyEvent event = new KeyEvent(0, 0, 0, KeyEvent.KEYCODE_DEL, 0, 0, 0, 0, KeyEvent.KEYCODE_ENDCALL);
                    et_comment.dispatchKeyEvent(event);
                }
            }
        });

        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getData();
            }
        });
        handler = new Handler(Looper.getMainLooper());
        circleView.setListener(new FriendCircleListener() {

            @Override
            public void showAllToggle() {
                circleView.update(position,mCircle);
            }

            @Override
            public void onAvatarClick(int position, String id) {
                ActivityUtil.create(mContext)
                        .go(MineCircleActivity.class)
                        .put("id",id)
                        .start();
            }

            @Override
            public void onCommentButtonClick(int position, Comment comment) {
                Utils.systemErr("--onCommentButtonClick->");
                et_comment.requestFocus();
                toUser = comment.getId();
                type = 0;
                commentId = null;
                //延迟100毫秒弹出键盘
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Utils.showSoftWindow(mContext,et_comment);
                    }
                },100);

//                ActivityUtil.create(mContext)
//                        .go(EditCommentActivity.class)
//                        .put("id",circle.getId())
//                        .put("toUser",comment.getId())
//                        .startForResult(12);
            }

            @Override
            public void onPraiseButtonClick(int position, String id) {
                praise(mCircle,id);
            }

            @Override
            public void onCommentItemClick(int position, Comment comment) {
                et_comment.requestFocus();
                Utils.showSoftWindow(mContext,et_comment);
                toUser = comment.getId();
                commentId = comment.getCommentId();
                if (TextUtils.equals(toUser, userId)) {
                    et_comment.setHint("发表评论...");
                } else {
                    et_comment.setHint("回复"+comment.getFromNick());
                }
                type = 1;
            }

            @Override
            public void onLinkNameClick(String id) {

            }

            @Override
            public void onDelete(int position, String id) {
                deleteCircle(position,id);
            }
        });

        showDialog();
        getData();
    }

    void showSoftWindow(){
        int cType = getIntent().getIntExtra("type", 0);
        //从看图文详情大图页面跳转。
        if (cType == 1) {
            et_comment.requestFocus();
            //延迟100毫秒弹出键盘
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    Utils.showSoftWindow(mContext,et_comment);
                }
            },100);
        }
    }

    void getData(){
        HttpManager.circlesInfo(id,userId)
                .subscribe(new ResultDataSubscriber<Circle>(this) {
                    @Override
                    public void onSuccess(String msg, Circle circle) {
                        mCircle = circle;
                        toUser = mCircle.getAuthorId();
                        mSwipeRefreshLayout.setRefreshing(false);
                        circleView.update(position,circle);
                        showSoftWindow();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        mSwipeRefreshLayout.setRefreshing(false);
                    }
                });
    }

    @OnTextChanged(R.id.et_comment)
    void onCommentChanged(Editable s){
        if (TextUtils.isEmpty(s)) {
            tv_action.setVisibility(View.GONE);
        } else {
            tv_action.setVisibility(View.VISIBLE);
        }
    }

    private void deleteCircle(final int position, String id){
        BaseActivity activity = null;
        if (mContext instanceof BaseActivity) {
            activity = (BaseActivity) mContext;
            activity.showDialog();
        }
        HttpManager.delSpoke(id,"C")
                .subscribe(new ResultDataSubscriber<JsonObject>(activity) {
                    @Override
                    public void onSuccess(String msg, JsonObject jsonObject) {
                        Intent intent = new Intent();
                        intent.putExtra("position",position);
                        setResult(RESULT_DELETE,intent);
                        finish();
                    }
                });
    }

    private void praise(final Circle circle, String id){
        if (circle == null) {
            return;
        }
        BaseActivity activity = null;
        if (mContext instanceof BaseActivity) {
            activity = (BaseActivity) mContext;
            activity.showDialog();
        }
        HttpManager.clickPraise(userId,"C",id)
                .subscribe(new ResultDataSubscriber<LikeData>(activity) {
                    @Override
                    public void onSuccess(String msg, LikeData likeData) {
                        showToast(msg);
                        //当前用户行为 1：取消点赞 0：点赞
                        if (likeData.getClickPraise() == 0) {
                            int num = circle.getLikeNum();
                            if (num < 4) {
                                circle.getLikeList().add(likeData.getLike());
                            }
                            num++;
                            circle.setLikeNum(num);
                            circle.setClickPraise(1);
                        } else {
                            int num = circle.getLikeNum();
                            List<Like> likes = circle.getLikeList();
                            for (Like like : likes) {
                                if (like.getUserID().equals(userId)) {
                                    likes.remove(like);
                                    break;
                                }
                            }
                            num--;
                            if (num < 0) {
                                num = 0;
                            }
                            circle.setLikeNum(num);
                            circle.setClickPraise(0);
                        }
                        circleView.update(position,mCircle);
                    }
                });
    }

    void addComment(){
        String content = et_comment.getText().toString().trim();
        if (TextUtils.isEmpty(content)) {
            showToast("发送文字不能为空");
            return;
        }
        showDialog();
        HttpManager.addComment(userId,"C",id,toUser,content,type,"0",commentId)
                .subscribe(new ResultDataSubscriber<Comment>(this) {
                    @Override
                    public void onSuccess(String msg, Comment comment) {
                        showToast(msg);
                        mCircle.getCommentList().add(comment);
                        int num = mCircle.getCommentNum();
                        mCircle.setCommentNum(num+1);
                        circleView.update(position,mCircle);
                        Utils.hideSoftWindow(mContext,et_comment);
                        emojiconMenu.setVisibility(View.GONE);
                        et_comment.setText("");
                        et_comment.setHint("发表评论...");
                        et_comment.clearFocus();
                    }
                });
    }

    @OnClick({R.id.expressionView,R.id.et_comment,R.id.tv_action})
    void onViewClick(View v) {
        switch (v.getId()) {
            case R.id.expressionView:

                Utils.hideSoftWindow(this,v);
                if (emojiconMenu.getVisibility() == View.VISIBLE) {
                    emojiconMenu.setVisibility(View.GONE);
                } else {
                    emojiconMenu.setVisibility(View.VISIBLE);
                    et_comment.requestFocus();
                }

                break;
            case R.id.et_comment:
                emojiconMenu.setVisibility(View.GONE);
                break;
            case R.id.tv_action:
                addComment();
                break;
        }
    }
}
